package com.shujia.flink.sql

import org.apache.flink.streaming.api.scala.StreamExecutionEnvironment
import org.apache.flink.table.api.EnvironmentSettings
import org.apache.flink.table.api.bridge.scala.StreamTableEnvironment

object Demo10EventTImeWindow {
  def main(args: Array[String]): Unit = {
    val bsEnv: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment

    bsEnv.setParallelism(1)

    val bsSettings: EnvironmentSettings = EnvironmentSettings
      .newInstance()
      .useBlinkPlanner() //使用blink计划器
      .inStreamingMode() //使用流模型
      .build()

    //创建flink sql的执行环境
    val bsTableEnv: StreamTableEnvironment = StreamTableEnvironment.create(bsEnv, bsSettings)


    /**
      * Java,"2021-11-03 08:45:10"
      * Java,"2021-11-03 08:45:11"
      * Java,"2021-11-03 08:45:12"
      * Java,"2021-11-03 08:45:13"
      * Java,"2021-11-03 08:45:15"
      * Java,"2021-11-03 08:45:16"
      * Java,"2021-11-03 08:45:20"
      */


    bsTableEnv.executeSql(
      """
        |
        |CREATE TABLE words (
        | word STRING,
        | ts TIMESTAMP(3),
        | WATERMARK FOR ts AS ts - INTERVAL '5' SECOND
        |) WITH (
        | 'connector' = 'kafka',
        | 'topic' = 'event_time',
        | 'properties.bootstrap.servers' = 'master:9092,node1:9092,node2:9092',
        | 'properties.group.id' = 'testGroup',
        | 'format' = 'csv',
        | 'scan.startup.mode' = 'earliest-offset',
        | 'csv.field-delimiter'=','
        |)
        |
      """.stripMargin)


    bsTableEnv.executeSql(
      """
        |CREATE TABLE print_table
        | (
        | word STRING,
        | end_time TIMESTAMP(3),
        | c BIGINT
        | )
        |WITH ('connector' = 'print')
        |
      """.stripMargin)


    bsTableEnv.executeSql(
      """
        |insert into print_table
        |
        |
        |select
        |word,
        |TUMBLE_END(ts, INTERVAL '5' SECOND) end_time,
        |count(1) c
        |from
        |words
        |group by word,TUMBLE(ts, INTERVAL '5' SECOND)
        |
      """.stripMargin)


  }

}
